package com.mrd.gtimp.business.service;

import com.mrd.base.BaseBiz;
import com.mrd.constant.HgDataConstants;
import com.mrd.exception.QueryException;
import com.mrd.framework.ui.Jqgrid;
import com.mrd.framework.ui.filter.Filter;
import com.mrd.framework.ui.filter.SearchRule;
import com.mrd.framework.ui.filter.SearchRuleOption;
import com.mrd.gtimp.business.entity.HgData;
import com.mrd.spring.repository.BaseRepository;

import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;

import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

/**
 * <p> application name: gtimp <p> copyright: Copyright@2012 明睿达科技有限公司
 */

/**
 * @author qiul
 */
@Service
public class HgDataBiz extends BaseBiz<HgData> {


    @Resource
    // 该处指定注入BaseRepository的dao对象
    @Qualifier("hgDataDao")
    public void setBaseRepository(BaseRepository<HgData, String> baseRepository) {
        super.baseRepository = baseRepository;
    }


    /**
     * 查询在线下单 （下拉框）1.币制 2. 征免 3.运输方式 4.单证代码 等等
     */
    public Map<String, Map<String, List<HgData>>> findCurrencySystem() throws QueryException {
        Map<String, List<HgData>> data = new HashMap<>();
        List<String> HgConstants = addHgType();
        for (String hgConstant : HgConstants) {
            data.put(hgConstant, new ArrayList<>());
        }
        Filter filters = new Filter();
        filters.addRule(new SearchRule("type", SearchRuleOption.in, HgConstants));
        Sort.Order order = new Sort.Order("code");
        Pageable pageable = new PageRequest(0, 10000, new Sort(order));
        Jqgrid jqgrid = new Jqgrid(filters, pageable);
        List<HgData> hgDatas = findByJqgrid(jqgrid).getContent();
        for (HgData hgData : hgDatas) {
            List<HgData> hgDataList = data.get(hgData.getType());
            if (hgDataList != null) {
                hgDataList.add(hgData);
            }
        }
        //适应改造之前的结构
        Map<String, Map<String, List<HgData>>> m = new HashMap<>();
        m.put("data", data);
        return m;
    }


    private List<String> addHgType() {
        List<String> hgType = new ArrayList<String>();
        Class<HgDataConstants> c = HgDataConstants.class;
        HgDataConstants hgDataConstants = new HgDataConstants();
        Field[] fields = c.getFields();
        for (Field field : fields) {
            try {
                hgType.add((String) field.get(hgDataConstants));
            } catch (IllegalArgumentException e) {
                e.printStackTrace();
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            }
        }
        return hgType;
    }


}
